package com.yaoli.ajob;

import java.util.Arrays;

/**
 * Created by siemens on 4/11/2017.
 *
 * 思路：比如 12443322，从最后一个数字 开始 找到第一个比他小的 数字，交换，判断是比 Integer.MAX_VALUE大 ，大的话就不是Integer排除
 *
 *
 */
public class _556_NextGreaterElementIII {
    public static void main(String[] args) {
        _556_NextGreaterElementIII nextGreaterElementIII = new _556_NextGreaterElementIII();

        //System.out.println(nextGreaterElementIII.nextGreaterElement(12443322));
        System.out.println(nextGreaterElementIII.nextGreaterElement(12));
        //System.out.println(nextGreaterElementIII.nextGreaterElement(12443322));

    }

    public int nextGreaterElement(int n) {
        char [] sets = String.valueOf(n).toCharArray();

        int i = 0;
        int j = 0;

        boolean flag = false;

        Long maxIntege = Long.valueOf(Integer.MAX_VALUE);

        int min = Integer.MAX_VALUE;
        int recordi = 0;
        int recordj = 0;

        for(i = sets.length - 1; i >=0 ;i --){
            for(j = i - 1 ; j >= 0 ; j--){
                if(sets[i] > sets[j]){
                    swap(sets,i,j);
                    long temp1 = Long.valueOf(String.valueOf(sets));
                    if(temp1 > maxIntege){
                        continue;
                    }else{
                        if(temp1 < min && temp1 > n){
                            flag = true;
                            min =(int)temp1;
                            recordi = i;
                            recordj = j;
                        }
                    }
                    swap(sets,i,j);
                }
            }
        }

        if(flag == false){
            return -1;
        }

        swap(sets,recordi,recordj);

        int len = sets.length - recordj - 1;

        char [] tempSet = new char[len];

        for(int p = recordj + 1 , q = 0; q < len; p++,q++){
            tempSet[q] = sets[p];
        }

        Arrays.sort(tempSet);

        for(int p = recordj + 1 , q = 0 ; q < len ; p++ ,q++){
            sets[p] = tempSet[q];
        }

        return Integer.valueOf(String.valueOf(sets));
    }

    public void swap(char sets[] , int i , int j ){
        char temp = sets[j];
        sets[j] = sets[i];
        sets[i] = temp;
    }
}
